﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections.Concurrent;
using System.Threading;

namespace Cnblogs.ConcurrentDictionary.Test
{
    class Program
    {
        #region v1.0
        //private static int _runCount=0;
        //private static readonly ConcurrentDictionary<string, string> _dic = new ConcurrentDictionary<string, string>();
        //static void Main(string[] args)
        //{
        //    var task1 = Task.Run(()=>PrintValue("test"));
        //    var task2 = Task.Run(()=>PrintValue("cnblogs"));
        //    Task.WaitAll(task1,task2);
        //    PrintValue("hahaha");
        //    Console.WriteLine(_runCount);
        //    Console.ReadKey();
        //}
        //public static void PrintValue(string ValuePrint)
        //{
        //    var valueFound = _dic.GetOrAdd("key",x=>{
        //        Interlocked.Increment(ref _runCount);
        //        Thread.Sleep(100);
        //        return ValuePrint;
        //    });
        //    Console.WriteLine(valueFound);
        //}
        #endregion
        #region V2.0
        private static int _runCount = 0;
        private static readonly ConcurrentDictionary<string, Lazy<string>> _Lazydic = new ConcurrentDictionary<string, Lazy<string>>();
        static void Main(string[] args)
        {
            var task1 = Task.Run(() => PrintValue("test"));
            var task2 = Task.Run(() => PrintValue("cnblogs"));
            Task.WaitAll(task1, task2);
            PrintValue("hahaha");
            Console.WriteLine(_runCount);
            Console.ReadKey();
        }
        public static void PrintValue(string ValuePrint)
        {
            var valueFound = _Lazydic.GetOrAdd("key", x => new Lazy<string>(()=> {
                Interlocked.Increment(ref _runCount);
                Thread.Sleep(100);
                return ValuePrint;
            }));
            Console.WriteLine(valueFound.Value);
        }
        #endregion
    }
}
